package com.example.rpc_core.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.setting.dialect.Props;
import cn.hutool.setting.yaml.YamlUtil;

import java.util.Map;


/**
 * 配置Rpc读取文件的配置类(只支持yaml和properties文件)
 */
public class RpcConfigUtil {
    /**
     * 读取配置文件
     * @param clazz
     * @param prefix
     * @param fileType
     * @return
     * @param <T>
     */
    public static <T> T loadConfig(Class<T> clazz, String prefix,String fileType) {
        return loadConfig(clazz, prefix, "", fileType);
    }

    /**
     * 读取配置文件
     * @param clazz
     * @param prefix
     * @param environment
     * @param fileType
     * @return
     * @param <T>
     */
    public static <T> T loadConfig(Class<T> clazz, String prefix, String environment,String fileType)  {
        StringBuilder stringBuilder=new StringBuilder("application");
        if (environment!=null && !environment.isEmpty()){
            stringBuilder.append("_"+environment);
        }
            //配置文件类型
            stringBuilder.append(".").append(fileType);
            //统一转为小写
            String  filename  = stringBuilder.toString().toLowerCase();
        try {
            //配置yaml文件类型
            if("yaml".equalsIgnoreCase(fileType) || "yml".equalsIgnoreCase(fileType)){
                Map<String, Object> map = YamlUtil.loadByPath(filename, Map.class);
                if (!prefix.isEmpty()) {
                    String prefixKey = prefix.replace(".", "");
                    map = (Map<String, Object>) map.get(prefixKey);
                }
                return BeanUtil.toBean(map, clazz);
            }
            else{
                //配置properties文件类型
                Props props = new Props(filename);
                    return props.toBean(clazz, prefix);
                }

        } catch (Exception e) {
            throw new RuntimeException("失败导入配置 " + stringBuilder, e);
        }
    }

}